window.pub = {


    textToParagraphedHtml: function (text) {
        if (!text) {
            return '<p></p>';
        }
        var ps = text.split(/\n/);
        var html = '';
        for (var n = 0; n < ps.length; n++) {
            html += '<p>' + kendo.htmlEncode(ps[n]) + '</p>';
        }
        return html;
    },

    lastOf: function (arr) {
        if (!arr || !arr.length) {
            return undefined;
        }
        return arr[arr.length - 1];
    },

    firstOf: function (arr) {
        if (!arr || !arr.length) {
            return undefined;
        }
        return arr[0];
    },

    parseParams: function (str) {
        if (str === undefined) {
            var qs = null;
            var href = window.location.href;
            if (href.indexOf("#") != -1) {
                qs = href.substring(href.indexOf("?"));
                str = qs;
            } else {
                qs = window.location.search;
                if (qs) {
                    str = qs.substring(1);
                }
            }
        }
        if (typeof str !== 'string') {
            return {};
        }

        var qPos = str.indexOf('?');
        if (qPos != -1) {
            str = str.substr(qPos + 1);
        }

        str = str.trim().replace(/^(\?|#|&)/, '');

        if (!str) {
            return {};
        }


        return str.split('&').reduce(function (ret, param) {
            var parts = param.replace(/\+/g, ' ').split('=');
            var key = parts[0];
            var val = parts[1];

            key = decodeURIComponent(key);
            // missing `=` should be `null`:
            // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
            val = val === undefined ? null : decodeURIComponent(val);

            if (!ret.hasOwnProperty(key)) {
                ret[key] = val;
            } else if (Array.isArray(ret[key])) {
                ret[key].push(val);
            } else {
                ret[key] = [ret[key], val];
            }

            return ret;
        }, {});
    },

    date: {
        today: function () {
            var date = new Date();
            date.setHours(0, 0, 0, 0);
            return date;
        },
        addDay: function (date, diff) {
            if (typeof date == 'number') {
                date = pub.date.fromIntDate(date);
            }
            var date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate() + diff);
            return date1;
        },
        toIntDate: function (date) {
            return date.getFullYear() * 10000 + (date.getMonth() + 1) * 100 + date.getDate();
        },
        fromIntDate: function (nDate) {
            if (!nDate || nDate == 0) {
                return null;
            }
            var y = Math.floor(nDate / 10000);
            var m = Math.floor((nDate - y * 10000) / 100);
            var d = nDate % 100;
            return new Date(y, m - 1, d);
        },
        formatLocalDate: function (date) {
            if (typeof(date) == 'number') {
                date = pub.date.fromIntDate(date);
            }
            return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
        },
        formatDate: function (date) {
            if (typeof(date) == 'number') {
                date = pub.date.fromIntDate(date);
            }
            var m = (date.getMonth() + 1);
            if (m < 10) {
                m = '0' + m;
            }
            var d = date.getDate();
            if (d < 10) {
                d = '0' + d;
            }
            return date.getFullYear() + '-' + m + '-' + d;
        },
        getWeekDay: function (date) {
            if (typeof(date) == 'number') {
                date = pub.date.fromIntDate(date);
            }
            var weekDayNames = ['天', '一', '二', '三', '四', '五', '六'];
            return '星期' + weekDayNames[date.getDay()];
        },
        formatTime: function (time) {
            if (!time || !time.getTime()) {
                return '';
            }
            var n = time.getMinutes();
            var sTime = time.getHours() + ':' + (n < 10 ? '0' : '') + n;
            return sTime;
        },
        formatDateTime: function (time) {
            var date = new Date(time);
            return pub.date.formatDate(date) + ' ' + pub.date.formatTime(date);
        },
        isSameDay: function (date1, date2) {
            return date1.getFullYear() == date2.getFullYear() &&
                date1.getMonth() == date2.getMonth() &&
                date1.getDate() == date2.getDate();
        },
        formatHM: function (mins) {// param 分钟
            var h = Math.floor(mins / 60);
            h = h < 10 ? '0' + h : h;
            var m = mins % 60;
            m = m < 10 ? '0' + m : m;
            return '' + h + ':' + m;
        },
        formatHHMM: function (date) {
            if (typeof(date) == 'number') {
                date = new Date(date);
            }
            var hh = date.getHours().toString();
            var nn = date.getMinutes().toString();
            var ss = date.getSeconds().toString();
            var sTime = (hh[1] ? hh : '0' + hh[0]) + ':' +
                (nn[1] ? nn : '0' + nn);

            return sTime;
        },
        parse: function (str) {
            if (!str) {
                return new Date(0);
            }
            var pos = str.indexOf(' ');
            var sDate, sTime;
            if (pos != -1) {
                sDate = str.substr(0, pos);
                sTime = str.substr(pos + 1);
            }
            else {
                sDate = str;
            }
            var dateParts = sDate.split('-');
            if (dateParts.length != 3) {
                return new Date(0);
            }
            var y = Number(dateParts[0]) || 0;
            var m = Number(dateParts[1]) || 1;
            var d = Number(dateParts[2]) || 0;
            var h = 0, n = 0, s = 0, ms = 0;
            if (sTime) {
                pos = sTime.indexOf('.');
                if (pos != -1) {
                    ms = Number(sTime.substr(pos + 1)) || 0;
                    sTime = sTime.substr(0, pos);
                }
                var timeParts = sTime.split(':');
                if (timeParts.length == 3) {
                    h = Number(timeParts[0]) || 0;
                    n = Number(timeParts[1]) || 0;
                    s = Number(timeParts[2]) || 0;
                }
            }
            return new Date(y, m - 1, d, h, n, s, ms);
        },
        calcAge: function (birthDate) {
            birthDate = new Date(birthDate);
            var today = new Date();
            var age = today.getFullYear() - birthDate.getFullYear();
            var m = today.getMonth() - birthDate.getMonth();
            if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }
            return age;
        }
    },

    ///
    getCookie: function (sName) {
        sName = sName.toLowerCase();
        var oCrumbles = document.cookie.split(';');
        for (var i = 0; i < oCrumbles.length; i++) {
            var oPair = oCrumbles[i].split('=');
            var sKey = decodeURIComponent(oPair[0].trim().toLowerCase());
            var sValue = oPair.length > 1 ? oPair[1] : '';
            if (sKey == sName)
                return decodeURIComponent(sValue);
        }
        return '';
    },

    setCookie: function (sName, sValue, path) {
        var oDate = new Date();
        oDate.setYear(oDate.getFullYear() + 1);
        var sCookie = encodeURIComponent(sName) + '=' + encodeURIComponent(sValue) +
            ';expires=' + oDate.toGMTString();
        sCookie += ';path=' + (path || '') + '/';
        document.cookie = sCookie;
    },

    removeCookie: function (sName) {
        pub.setCookie(sName, '');
    },

    parseUrl: function (url) {
        var loc = document.createElement("a");
        loc.href = url;
        return {
            domain: loc.hostname,
            path: loc.pathname
        };
    },

    /**
     * 图片压缩，默认同比例压缩
     * @param {Object} path
     *   pc端传入的路径可以为相对路径，但是在移动端上必须传入的路径是照相图片储存的绝对路径
     * @param {Object} obj
     *   obj 对象 有 width， height， quality(0-1)
     * @param {Object} callback
     *   回调函数有一个参数，base64的字符串数据
     */
    dealImage: function (path, obj, callback) {
        var img = new Image();
        img.src = path;
        img.crossOrigin = "*";
        img.onload = function () {
            var that = this;
            // 默认按比例压缩
            var w = that.width,
                h = that.height,
                scale = w / h;
            w = obj.width || w;
            h = obj.height || (w / scale);
            var quality = 0.4;  // 默认图片质量为0.7
            //生成canvas
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                quality = obj.quality;
            }
            // quality值越小，所绘制出的图像越模糊
            var base64 = canvas.toDataURL('image/*', quality);
            // 回调函数返回base64的值
            callback(base64);
        }
    }

};